package com.bistu.xiong.tulingrobotchat.activities;


import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.StringRes;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.bistu.xiong.common.app.Activity;
import com.bistu.xiong.common.app.Application;
import com.bistu.xiong.common.widget.GalleryView;
import com.bistu.xiong.factory.data.DataSource;
import com.bistu.xiong.factory.data.RspCallback;
import com.bistu.xiong.factory.data.helper.CommunityHelper;
import com.bistu.xiong.factory.eventbus.MessageEvent;
import com.bistu.xiong.factory.model.api.community.SendUserPostModel;
import com.bistu.xiong.factory.net.UploadHelper;
import com.bistu.xiong.tulingrobotchat.R;
import com.bistu.xiong.tulingrobotchat.frags.account.media.GalleryChoosePicsFragment;
import com.bistu.xiong.tulingrobotchat.frags.account.media.GalleryFragment;
import com.github.ybq.android.spinkit.style.Wave;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.bistu.xiong.common.Common.getUriFromDrawable;


/**
 * SendUserPostActivity
 * 用于用户编辑和发送帖子，由于功能简单 这里Activity未采用MVP模式
 * Created by XiongXiaoJun on 2017/12/21.
 */
public class SendUserPostActivity extends Activity
        implements DataSource.Callback<String> ,GalleryView.SelectedAddListener{
    @BindView(R.id.content_edit)
    EditText contentEdit;

    @BindView(R.id.send_post)
    TextView sendPost;

    @BindView(R.id.choose_pics_recy)
    GalleryView choosePicsRecy;

    ProgressBar progressBar;

    //图片的地址（可以是多个，图片地址之间统一用;进行隔开）
    private String images;
    private List<String> imageList = new ArrayList<>();

    /**
     * SendUserPostActivity 显示的入口
     *
     * @param context 上下文
     */
    public static void show(Context context) {
        context.startActivity(new Intent(context, SendUserPostActivity.class));
    }

    @Override
    protected void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected int getCountentLayoutId() {
        return R.layout.activity_send_post;
    }

    @Override
    protected void initWidget() {
        super.initWidget();
        choosePicsRecy.setCurrenModel(GalleryView.ONLY_SHOW_PICS_MODEL,4);
        imageList.add(getUriFromDrawable(R.drawable.camera,this).toString());
        choosePicsRecy.setSource(imageList);
        choosePicsRecy.setAddListener(this);

        progressBar = (ProgressBar)findViewById(R.id.spin_kit);
        Wave wave = new Wave();
        progressBar.setIndeterminateDrawable(wave);
    }

    @OnClick(R.id.close)
    void closeSendPost(){
        finish();
    }

    //点击发送  调用接口
    @OnClick(R.id.send_post)
    void sendUserPost() {
        progressBar.setVisibility(View.VISIBLE);
        final String content = contentEdit.getText().toString();
        if (content==null||content.equals("")){
            toast("内容不能为空奥！");
            progressBar.setVisibility(View.GONE);
            return;
        }

        new UpPicsAsyncTask(content).execute();

    }


    /**
     * GalleryView中用户点击摄像头图标 要求添加图片时
     */
    @Override
    public void selectedAdd() {
        showChoosePics();
    }

    private void showChoosePics(){
        new GalleryChoosePicsFragment().show(getSupportFragmentManager(), GalleryFragment.class.getName());
    }



    @Override
    public void onDataLoaded(String s) {
        toast("发布成功");
        finish();
    }

    @Override
    public void onDataNotAvailable(@StringRes int strRes) {
        toast(strRes);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(MessageEvent event) {
        if (event.getType()==MessageEvent.GalleryChoosePicsFragment){
            imageList = (ArrayList<String>) event.getData();
            imageList.add(getUriFromDrawable(R.drawable.camera,this).toString());
            choosePicsRecy.setSource(imageList);
        }
    }

    private class UpPicsAsyncTask extends AsyncTask<List<String>,Integer,String>{
        String content;
        public UpPicsAsyncTask(String content) {
            this.content = content;
        }

        @Override
        protected String doInBackground(List<String>... lists) {
            String messagePics = "";
            for (int i=0;i<(imageList.size()-1);i++){
                String url = UploadHelper.uploadPortrait(imageList.get(i));
                if (TextUtils.isEmpty(url)) {
                    // 上传失败
                    toast(com.bistu.xiong.factory.R.string.data_upload_error);
                    return "";
                }else{
                    if (i!=0)
                        messagePics = messagePics+";";
                    messagePics = messagePics + url;
                }
            }
            return messagePics;
        }

        @Override
        protected void onPostExecute(String messagePics) {
            super.onPostExecute(messagePics);
            SendUserPostModel sendUserPostModel = new SendUserPostModel(messagePics,content);
            CommunityHelper.sendUserPost(sendUserPostModel,SendUserPostActivity.this);
        }
    }

}
